package com.example;

public class Main2 {
    public static void main(String[] args) {
        try {
            fun("123"); // 3
        } catch (Exception e) {
            System.out.println(123); // 捕获到异常对象后才执行
        } finally {
            System.out.println("finally"); //始终会运行
        }
        try {
            fun("abcd"); // 4
        } catch (Exception e) {
            System.out.println(123);
        }
        try {
            fun(null); // 报错
        } catch (Exception e) {
            System.out.println(123);
        }
        try {
            fun(""); // 0
        } catch (Exception e) {
            System.out.println(123);
        }

        try {
            fun2(30);
        } catch (Exception e) {
            System.out.println("出错啦");
        }
        try {
            fun2(230);
        } catch (Exception e) {
            System.out.println("出错啦");
            System.out.println(e.getMessage()); // 年龄不合理
        }
    }

    /* 抛出异常：添加到方法声明后 */
    public static void fun(String str) throws Exception {
        System.out.println(str.length()); // 字符串中的字符个数
    }

    public static void fun2(int age) throws Exception {
        if (age < 0 || age > 150) {
            // 主动抛错
            throw new AgeException("年龄不合理"); // 方法在此终止
        }
        System.out.println("年龄:" + age);
    }
}
